package com.wangxinrou.wangxinrou_surprisemeal.controller;

import com.wangxinrou.wangxinrou_surprisemeal.common.Result;
import com.wangxinrou.wangxinrou_surprisemeal.model.User;
import com.wangxinrou.wangxinrou_surprisemeal.service.UserService;
import io.swagger.v3.oas.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "注册一个新用户")
    public Result register(@Parameter(description = "用户对象", required = true) @RequestBody User user) {
        User register = userService.createUser(user);
        return Result.success(register);
    }

    @GetMapping("/findByName/{name}")
    @Operation(summary = "根据用户名查找用户", description = "通过用户名查找用户信息")
    public Result findByName(@Parameter(description = "用户名", required = true) @PathVariable String name) {
        User user = userService.findByName(name);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户信息", description = "更新已有用户的信息")
    public Result update(@Parameter(description = "用户对象", required = true) @RequestBody User user) {
        boolean success = userService.updateUser(user);
        if (success) {
            return Result.success("用户信息更新成功");
        }
        return Result.error("用户不存在，无法更新");
    }

    @DeleteMapping("/delete/{name}")
    @Operation(summary = "删除用户", description = "根据用户名删除用户")
    public Result delete(@Parameter(description = "用户名", required = true) @PathVariable String name) {
        boolean removed = userService.deleteUserByName(name);
        if (removed) {
            return Result.success("用户删除成功");
        }
        return Result.error("用户不存在，无法删除");
    }
}